<?php


namespace App\Http\Controllers\WebApi\Business;


use App\Models\ImAuthItems;

class AuthBusiness
{
    /**
     * 登录返回菜单
     */
    public function loginMenu($role_id)
    {
        $menuAuth = $this->menuAuth($role_id)->toArray();
        $menus = ImAuthItems::with(['children'])
            ->where('parent_id', 0)
            ->where('status', 1)
            ->orderBy('sort', 'asc')
            ->get();
        $authIds = array_map(function ($auth) {
            return $auth['id'];
        }, $menuAuth);
        foreach ($menus as &$val) {
            //一级菜单权限
            $val['has_auth'] = 0;
            if (1 === $role_id || in_array($val['id'], $authIds)) {
                $val['has_auth'] = 1;
            }
            //子菜单权限
            foreach ($val->children as &$child) {
                $child['has_auth'] = 0;
                if (1 === $role_id || in_array($child['id'], $authIds)) {
                    $child['has_auth'] = 1;
                }
            }
        }
        return $menus;
    }

    /**
     * 我的菜单权限
     * @return mixed
     */
    public function menuAuth($role_id)
    {
        $authCode = ImAuthItems::where('type', 1)
            ->whereHas('nowRoleAuth', function ($sql) use ($role_id) {
                $sql->where('role_id', $role_id)->select('id');
            })->select(['id', 'auth_code', 'name', 'logo', 'url'])->get();
        return $authCode;
    }

    /**
     * 操作权限
     * @return mixed
     */
    public function operationAuth($role_id)
    {
        $authCode = ImAuthItems::where('type', 2)->whereHas('nowRoleAuth', function ($sql) use ($role_id) {
            $sql->where('role_id', $role_id)->select('id');
        })->select(['id', 'parent_id', 'name', 'auth_code'])->get();
        return $authCode;
    }

    /**
     * 获取角色权限码
     * @param $role_id
     * @return mixed
     * @author an
     * @time 2021-12-07 18:58
     */
    public function allAuthCodes($role_id)
    {
        $query = new ImAuthItems();
        if ($role_id != 1) {
            $query = $query->whereHas('nowRoleAuth', function ($sql) use ($role_id) {
                $sql->where('role_id', $role_id)->select('id');
            });
        }
        $authCode = $query->select(['id', 'auth_code', 'name', 'logo', 'url'])
            ->get()->map(function ($val) {
                return $val['auth_code'];
            });
        return $authCode;
    }
}
